package com.ykht.proj.comsrv.utils.msgutil.QrCodeUtil;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ykht.proj.admin.api.entity.SysSocialDetails;
import com.ykht.proj.admin.api.feign.RemoteSysSocialDetailsService;
import com.ykht.proj.common.core.constant.SecurityConstants;
import com.ykht.proj.common.core.constant.enums.LoginTypeEnum;
import com.ykht.proj.common.core.util.R;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class QRcodeUtil {

	@Resource
	private RemoteSysSocialDetailsService remoteSysSocialDetailsService;

	public String QRcode(String scene,String page,String bcType) {
		byte[] result = QRcode4Byte(scene,page,bcType);
		String base64 = Base64.encodeBase64String(result);
//		log.info("小程序二维码：{}",base64);
		//data:image/jpeg;base64,加上base64 可以再浏览器上直接打开
		return base64;
	}
	public byte[] QRcode4Byte(String scene,String page,String bcType) {

		String tokenUrl =null;
		if ("c".equals(bcType)){
			R<SysSocialDetails> r = remoteSysSocialDetailsService.getOne(LoginTypeEnum.MINI_C.getType(), SecurityConstants.FROM_IN);
			tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+r.getData().getAppId()+"&secret="+r.getData().getAppSecret();
//			tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx66d31936b1685d4d&secret=ece7f92e5b0f127dc062132ac52b3050";
		}else {
			R<SysSocialDetails> r = remoteSysSocialDetailsService.getOne(LoginTypeEnum.MINI_APP.getType(), SecurityConstants.FROM_IN);
			tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+r.getData().getAppId()+"&secret="+r.getData().getAppSecret();
		}
		String data = HttpUtil.get(tokenUrl);
		String access_token = JSONUtil.parseObj(data).getStr("access_token");
		String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;
		HttpResponse response = HttpUtil.createPost(url)
				.body(JSONUtil.createObj().putOpt("scene",scene).putOpt("page",page).toString())
				.execute();
		byte[] result = response.bodyBytes();
//		System.out.println(Base64.encodeBase64String(result));
		return result;
	}


}
